<template>
	<view class="lee-wrap">
		<view class="p10">
			<u--input prefixIcon="search" placeholder="请输入合伙人名称" border="none" shape="circle"
				:customStyle="{background:'#f5f5f5',height:'60rpx',paddingLeft:'20rpx'}" v-model="newParams.name"
				@input="toSearch">
			</u--input>
		</view>

		<view class="page-view">
			<view class="class-item" :id="'item' + index" v-for="(item , index) in tableData" :key="index">
				<view class="card c3 mb10 cshow">
					<view class="content">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view class="content-text" style="font-size: 36rpx;font-weight: 700;">
								#{{ item.id }}
							</view>
							<view class="content-text" style="display: flex;align-items: center;">状态：
								<u-tag :type="statusList[item.status].type" size="mini" plain
									:text="statusList[item.status].name">
								</u-tag>
							</view>
						</view>
						<view class="content-text">合伙人名称：{{item.name}}</view>
						<view class="content-text">OEM：{{item.oem_name}}
						</view>
						<view class="content-text">
							代理：{{item.agent_name}}</view>
						<view class="content-text">
							手机号：{{item.phone}}</view>
						<view class="content-text">
							抽佣比例：{{item.commission_ratio}}</view>
						<u-collapse :border="false">
							<u-collapse-item title="收款账户" name="rmb-circle" icon="setting">
								<view class="setting">
									<button type="primary" @click="jinjian(item)" size="mini"
										class="storeBtn">收款账户</button>
									<button type="primary" @click="getjinjianInfo(item)" size="mini"
										class="storeBtn">查询收款账户</button>
									<button type="primary" @click="getyue(item)" size="mini"
										class="storeBtn">查询余额</button>
								</view>
							</u-collapse-item>
						</u-collapse>
						<u-collapse :border="false">
							<u-collapse-item title="操作" name="Docs guide" icon="setting">
								<view class="setting">
									<button type="primary" @click="edit(item)" size="mini"
										v-if="menus.includes('partner/partner/edit')" class="storeBtn">编辑</button>
									<button type="primary" @click="qiAndJin(item,0)" size="mini"
										v-if="item.status == 1 && menus.includes('partner/partner/setPartnerStatus')"
										class="storeBtn">启用</button>
									<button type="primary" @click="qiAndJin(item,1)" size="mini"
										v-if="item.status == 0 && menus.includes('partner/partner/setPartnerStatus')"
										class="storeBtn">禁用</button>
								</view>
							</u-collapse-item>
						</u-collapse>
					</view>
				</view>
			</view>
			<view style="width: 100%;height: 200rpx;"></view>
			<view v-if="tableData.length==0" class="np f-c-c">
				<view class="iconfont icon-queshengtu cb" style="font-size: 90rpx;"></view>
				<view class="f12 cb mt20">暂无合伙人</view>
			</view>
			<view class="navbar2 bt f-row">
				<view class="f-c" style="width: 168rpx;background: #FBFBFB;">员工号设置</view>
				<view class="f-1 f-row bf">
					<template v-for="(v, i) in navs">
						<view class="f-1 f-y-c" @click="djTab(v)" :key="i" v-if="menus.includes(v.role)">
							<view class="wh f-c f-y-c">
								<text class="cf7c mr10" :style="{ color: subColor ,fontSize:'38rpx'}"
									:class="['icon' + v.i, 'iconfont f20']"></text>
								<view class="">{{ v.t }}</view>
							</view>
						</view>
					</template>
				</view>
			</view>
		</view>
		<u-popup :show="partnerShow" @close="partnerShow = false" mode="center" :round="10"
			:safeAreaInsetBottom="false">
			<view class="popup">
				<u--form :model="ruleForm" ref="ruleFormRef" labelWidth="70" :rules="rules">
					<u-form-item label="代理" prop="agent_id" v-if="adminInfo.type == 2">
						<uni-data-select v-model="ruleForm.agent_id" :localdata="agent_idoptions" disabled
							:clear="false"></uni-data-select>
					</u-form-item>
					<u-form-item label="合伙人名称" prop="name" ref="item1">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.name"></u--input>
					</u-form-item>
					<u-form-item label="抽佣比例 " prop="commission_ratio" ref="item1">
						<u-number-box v-model="ruleForm.commission_ratio" :decimal-length="2" :step="0.01" longPress
							inputWidth="40" :min="0" :max="30"></u-number-box>
						<span class="ml10">(百分比/15%)</span>
					</u-form-item>
					<u-form-item label="允许添加门店数量" prop="store_sum">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.store_sum"
							type="number"></u--input>
					</u-form-item>
					<u-form-item label="商品上传数量" v-if="menus.includes('store/store/productNumber')">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.upload_product_number"
							type="number"></u--input>
					</u-form-item>
					<u-form-item label="手机号 " prop="phone" ref="item1">
						<u--input placeholder="请输入内容" border="surround" v-model="ruleForm.phone"></u--input>
					</u-form-item>
					<u-form-item label="LOGO" ref="item1" label-width="50">
						<u-upload :fileList="ruleForm.logo_img" @afterRead="afterRead" @delete="deletePic" name="1"
							multiple :maxCount="3"></u-upload>
					</u-form-item>
					<u-form-item label="营业执照" ref="item1" label-width="50">
						<u-upload :fileList="ruleForm.bus_img" @afterRead="afterRead" @delete="deletePic" name="2"
							multiple :maxCount="3"></u-upload>
					</u-form-item>
				</u--form>
				<view class="footer">
					<u-button text="确定" type='primary' @click="submit"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapState,
	} from 'vuex'
	import COS from 'cos-wx-sdk-v5';
	import CryptoJS from 'crypto-js';
	import site from '@/custom/siteroot.js';
	export default {
		data() {
			return {
				cos: null, // COS SDK 实例
				newParams: {
					page: 1,
					limit: 20,
					name: '',
					phone: ''
				},
				hasLoadedData: false,
				tableData: [],
				statusList: {
					'0': {
						type: 'success',
						name: '正常',
					},
					'1': {
						type: 'error',
						name: '禁用',
					},
				},
				partnerShow: false,
				adminInfo: uni.getStorageSync("adminInfo"),
				subColor: uni.getStorageSync("subject_color"),
				ruleForm: {
					agent_id: '',
					name: '',
					logo_img: [],
					bus_img: [],
					phone: '',
					commission_ratio: 0,
					store_sum: 0,
					upload_product_number: 0
				},
				addForm: {
					agent_id: '',
					name: '',
					logo_img: [],
					bus_img: [],
					phone: '',
					commission_ratio: 0,
					store_sum: 0,
					upload_product_number: 0
				},
				rules: {
					name: [{
						required: true,
						message: '请填写',
						trigger: 'blur'
					}],
					phone: [{
							required: true,
							message: '请填写',
							trigger: 'blur'
						},
						{
							min: 11,
							max: 11,
							message: '手机格式不正确',
							trigger: 'blur'
						},
					],
				},
				navs: [{
					i: '-jiahao',
					k: 'xjsp',
					url: 'xzlx',
					t: '添加员工号',
					role: 'partner/partner/add'
				}],
				addAndEditStatus: '',
				agent_idoptions: []
			}
		},
		computed: {
			...mapState({
				menus: state => state.menus,
			}),
		},
		onReady() {
			this.$refs.ruleFormRef.setRules(this.rules)
		},
		mounted() {
			// 初始化 COS SDK
			this.initCOS();
		},
		methods: {
			getlists() {
				uni.showLoading()
				this.beg.request({
					url: '/admin/partner.Partner/index',
					method: 'post',
					data: this.newParams
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						res.data.data.forEach((v) => {
							v.bus_img = JSON.parse(v.bus_img)
							v.bus_img = v.bus_img.map(item => ({
								url: site.siteimgroot + item,
								src: item
							}));
							v.logo_img = JSON.parse(v.logo_img)
							v.logo_img = v.logo_img.map(item => ({
								url: siteroot.siteimgroot + item,
								src: item
							}));
						})
						let newData = res.data.data.map(item => this.replaceNulls(item));
						if (!this.hasLoadedData) {
							this.tableData = newData;
							this.hasLoadedData = true;
						} else {
							this.tableData = this.tableData.concat(newData);
						}
					}
				})
			},
			replaceNulls(data) {
				if (data === null || data === undefined) {
					return '';
				}
				if (typeof data === 'object' && !Array.isArray(data)) {
					return Object.keys(data).reduce((obj, key) => {
						obj[key] = this.replaceNulls(data[key]);
						return obj;
					}, {});
				}
				if (Array.isArray(data)) {
					return data.map(item => this.replaceNulls(item));
				}
				return data;
			},
			toSearch() {
				this.hasLoadedData = false;
				this.getlists()
			},
			edit(val) {
				this.ruleForm = val
				this.partnerShow = true
				this.addAndEditStatus = 0
			},
			qiAndJin(val, status) {
				let name = ''
				if (status == 0) {
					name = '启用'
				} else if (status == 1) {
					name = '禁用'
				}
				uni.showModal({
					title: '提示',
					content: `确定${name}该门店？`,
					success: (res) => {
						if (res.confirm) {
							this.beg.request({
									url: '/admin/partner.Partner/setPartnerStatus',
									method: 'post',
									data: {
										id: val.id,
										status: status,
									}
								}).then((res) => {
									if (res.code == 1) {
										uni.$u.toast(res.msg)
										setTimeout(res => {
											this.hasLoadedData = false;
											this.newParams.page = 1
											this.getlists()
										}, 800)
									} else {
										uni.$u.toast(res.msg)
									}
								})
								.catch(() => {})
						}
					}
				})
			},
			// 进件
			jinjian(item) {
				this.beg.request({
					url: '/index.php/admin/partner.Partner/app_add_sub_merchant',
					method: 'post',
					data: {
						id: item.id
					}
				}).then(res => {
					if (res.code == 1) {
						let content = res.data
						uni.showModal({
							title: '提示',
							content: '点击复制链接到浏览器打开',
							confirmText: '复制链接',
							success: function(res) {
								if (res.confirm) {
									uni.setClipboardData({
										data: content,
										success: () => {
											uni.showToast({
												title: '已复制到剪贴板',
												icon: 'none',
												duration: 2000
											});
										}
									});
								}
							}
						});
					}
				})
			},
			getjinjianInfo(val) {
				this.beg.request({
						url: '/index.php/admin/partner.Partner/query_store_pay_info',
						method: 'post',
						data: {
							id: val.id
						}
					})
					.then((res) => {
						if (res.code == 1) {
							this.beg.request({
									url: '/index.php/admin/partner.Partner/app_add_sub_merchant',
									method: 'post',
									data: {
										id: val.id
									}
								})
								.then((res) => {
									if (res.code == 1) {
										let content = res.data
										uni.showModal({
											title: '提示',
											content: '点击复制链接到浏览器打开',
											confirmText: '复制链接',
											success: function(res) {
												if (res.confirm) {
													uni.setClipboardData({
														data: content,
														success: () => {
															uni.showToast({
																title: '已复制到剪贴板',
																icon: 'none',
																duration: 2000
															});
														}
													});
												}
											}
										});
									}
								})
								.catch(() => {})
						} else {}
					})
					.catch(() => {})
			},
			getyue(val) {
				this.beg.request({
						url: '/admin/store.Store/get_store_dy_balance',
						method: 'post',
						data: {
							id: val.id
						}
					})
					.then((res) => {
						if (res.code == 1) {
							let content = res.data
							uni.showModal({
								title: '提示',
								content: '点击复制链接到浏览器打开',
								confirmText: '复制链接',
								success: function(res) {
									if (res.confirm) {
										uni.setClipboardData({
											data: content,
											success: () => {
												uni.showToast({
													title: '已复制到剪贴板',
													icon: 'none',
													duration: 2000
												});
											}
										});
									}
								}
							});
						}
					})
					.catch((err) => {})
			},
			initCOS() {
				this.beg.request({
					url: '/admin/Cos/refreshToken',
					method: 'get',
				}).then(res => {
					// 获取临时密钥
					const {
						tmpSecretId,
						tmpSecretKey,
						sessionToken,
						startTime,
						expiredTime
					} = res.data;
					this.cos = new COS({
						getAuthorization: (options, callback) => {
							callback({
								TmpSecretId: tmpSecretId,
								TmpSecretKey: tmpSecretKey,
								SecurityToken: sessionToken,
								StartTime: startTime,
								ExpiredTime: expiredTime,
							});
						},
					});
				}).catch(error => {
					console.error('获取临时密钥失败:', error);
				});
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				if (event.name == 1) {
					let fileListLen = this.ruleForm.logo_img.length
					lists.map((item) => {
						this.ruleForm.logo_img.push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.handleFileInUploading(lists[i])
						let item = this.ruleForm.logo_img[fileListLen]
						this.ruleForm.logo_img.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result.headers.location,
							src: result.Location,
						}))
						fileListLen++;
					}
				} else {
					let fileListLen = this.ruleForm.bus_img.length
					lists.map((item) => {
						this.ruleForm.bus_img.push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.handleFileInUploading(lists[i])
						let item = this.ruleForm.bus_img[fileListLen]
						this.ruleForm.bus_img.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result.headers.location,
							src: result.Location,
						}))
						fileListLen++;
					}
				}

			},
			handleFileInUploading(event) {
				return new Promise((resolve, reject) => {
					const that = this
					const filePath = event.url
					const str = filePath.substr(filePath.lastIndexOf('/') + 1)
					const sha1Hash = CryptoJS.SHA1(str).toString();
					const fileName = '/storage/default/' + this.getCurrentDate() + '/' + str
					that.cos.uploadFile({
						Bucket: 'douyin-1325951894',
						Region: 'ap-beijing',
						Key: fileName,
						FilePath: filePath,
						SliceSize: 1024 * 1024 * 5,
						onFileFinish: function(err, data, options) {
							const fileUrl = '/' + options.Key
							that.beg.request({
								url: '/admin/Cos/callback',
								method: 'POST',
								data: {
									url: fileUrl,
									name: fileName,
									size: event.size,
									type: event.type,
									sha1: sha1Hash,
								},
							}).then(res => {
								if (res.code == 1) {
									setTimeout(() => {
										resolve(data)
									}, 500)
								}
							})
						},
					}, function(err, data, options) {
						// console.log(data,options)
					});
				})
			},
			deletePic(event) {
				if (event.name == 1) {
					this.ruleForm.logo_img.splice(event.index, 1)
				} else {
					this.ruleForm.bus_img.splice(event.index, 1)
				}

			},
			getCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0');
				const day = now.getDate().toString().padStart(2, '0');
				return year.toString() + month + day;
			},
			djTab() {
				this.partnerShow = true
				this.addAndEditStatus = 1
			},
			getOEMList() {
				this.beg.request({
						url: '/admin/select/get_select_data',
						data: {
							oem_id: this.adminInfo.oem_id,
							type: 2
						}
					}).then((res) => {
						if (res.code == 1) {
							var classfiy = []
							res.data.forEach(i => {
								classfiy.push({
									text: i.label
								})
							})
							this.agent_idoptions = classfiy;
						} else {
							uni.$u.toast(res.msg)
						}
					})
					.catch((err) => {})
			},
			submit() {
				this.$refs.ruleFormRef.validate().then(res => {
					const logoSrcs = [];
					this.ruleForm.logo_img.forEach((item) => {
						const exists = item.src.includes('douyin');
						if (exists) {
							const afterCom = item.src.substring(item.src.lastIndexOf('.com') + 4);
							logoSrcs.push(afterCom)
						} else {
							logoSrcs.push(item.src);
						}
					});
					this.ruleForm.logo_img = logoSrcs;
					const logoSrcs2 = [];
					this.ruleForm.bus_img.forEach((item) => {
						const exists = item.src.includes('douyin');
						if (exists) {
							const afterCom = item.src.substring(item.src.lastIndexOf('.com') + 4);
							logoSrcs2.push(afterCom)
						} else {
							logoSrcs2.push(item.src);
						}
					});
					this.ruleForm.bus_img = logoSrcs2;
					if (this.addAndEditStatus == 0) {
						this.beg.request({
							url: '/admin/partner.Partner/edit',
							method: 'post',
							data: this.ruleForm
						}).then(res => {
							if (res.code == 1) {
								uni.$u.toast(res.msg)
								this.partnerShow = false
								setTimeout(res => {
									this.hasLoadedData = false;
									this.newParams.page = 1
									this.getlists()
								}, 800)
							} else {
								uni.$u.toast(res.msg)
								this.partnerShow = false
							}
						})
					} else {
						this.beg.request({
							url: '/admin/partner.Partner/add',
							method: 'post',
							data: this.addForm
						}).then(res => {
							if (res.code == 1) {
								uni.$u.toast(res.msg)
								this.partnerShow = false
								setTimeout(res => {
									this.hasLoadedData = false;
									this.newParams.page = 1
									this.getlists()
								}, 800)
							} else {
								uni.$u.toast(res.msg)
								this.partnerShow = false
							}
						})
					}

				}).catch(errors => {
					console.log(errors);
				})
			},
		},
		onLoad() {
			this.getlists()
			this.getOEMList()
		}
	}
</script>
<style>
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	.page-view {
		background-color: #fff;
		padding: 16rpx;
	}

	.class-item {
		padding: 5rpx 5rpx;
		border-radius: 8rpx;
	}

	.content-text {
		margin-top: 10rpx;
	}

	.setting {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: center;
	}

	.storeBtn {
		background-color: #fdda34;
		color: #000;
		font-weight: 600;
		margin-top: 10rpx;
		margin-left: 20rpx;
	}

	.popup {
		width: 90vw;
		padding: 40rpx 20rpx;
	}

	.navbar2 {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100rpx;
		background: #fff;
		box-shadow: 0 0rpx 8rpx 4rpx rgba(0, 0, 0, 0.05);
	}
</style>